<!--消息自动回复-->
<template>
  <div id="thirdWechatAutoReply" class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-form :model="listQuery" :inline="true">
        <el-form-item>
          <application-key-select v-model="listQuery.appId" :type="listQuery.type" />
        </el-form-item>
      </el-form>
    </div>
    <el-tabs v-model="activeName" class="common-tabs">
      <el-tab-pane name="0">
        <span slot="label"><i class="el-icon-star-off" /> 关注时回复</span>
      </el-tab-pane>
      <el-tab-pane name="1">
        <span slot="label"><i class="el-icon-chat-line-round" /> 消息回复</span>
      </el-tab-pane>
      <el-tab-pane name="2">
        <span slot="label"><i class="el-icon-news" /> 关键词回复</span>
      </el-tab-pane>
    </el-tabs>
    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <div class="common-title">
          <h2>自动回复</h2>
        </div>
        <p class="common-tips">通过编辑内容或关键词规则，快速进行自动回复设置。</p>
        <p class="common-tips">设置自动回复之后，将立即对所有用户生效。</p>
        <p v-if="activeName==='1'" class="common-tips">接收同一种消息设置多种回复消息，系统会随机发送。</p>

        <table-toolbar v-if="activeName!=='0'" @create="handleCreate" @refresh="handleFilter" @remove="removeRecord" />
      </div>
      <template v-if="activeName==='0'">
        <div>
          <material-selection ref="materialSelection" v-model="thirdWechatAutoReplyRecord.replyContent" :app-id="listQuery.appId" />
        </div>
        <div style="text-align: center; padding-top: 50px;">
          <el-button type="primary" plain @click="handleFollowReplySave">保存</el-button>
          <!--<el-button type="danger" plain @click="handleSelectMaterial">删除回复</el-button>-->
        </div>
      </template>
      <el-table
        v-show="activeName==='1'"
        key="table1"
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="请求消息类型" prop="messageType" width="130" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.messageType==='image'">图片</span>
            <span v-if="scope.row.messageType==='voice'">音频</span>
            <span v-if="scope.row.messageType==='video'">视频</span>
            <span v-if="scope.row.messageType==='text'">文本</span>
            <span v-if="scope.row.messageType==='shortvideo'">小视频</span>
            <span v-if="scope.row.messageType==='location'">地理位置</span>
            <span v-if="scope.row.messageType==='link'">链接消息</span>
          </template>
        </el-table-column>
        <el-table-column label="回复消息类型" prop="resourceType" width="130" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.resourceType===0">图片</span>
            <span v-if="scope.row.resourceType===1">音频</span>
            <span v-if="scope.row.resourceType===2">视频</span>
            <span v-if="scope.row.resourceType===3">文本</span>
            <span v-if="scope.row.resourceType===4">图文</span>
          </template>
        </el-table-column>
        <el-table-column label="回复内容" prop="textContent" min-width="240" show-overflow-tooltip />
        <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90">
          <template slot-scope="scope">
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <el-table
        v-show="activeName==='2'"

        key="table2"
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>

        <el-table-column label="关键词" prop="keyword" sortable width="140" />
        <el-table-column label="匹配类型" prop="matchingType" width="130" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.matchingType===0" class="color-danger">半匹配</span>
            <span v-if="scope.row.matchingType===1" class="color-primary">全匹配</span>
          </template>
        </el-table-column>
        <el-table-column label="回复消息类型" prop="resourceType" width="130" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.resourceType===0">图片</span>
            <span v-if="scope.row.resourceType===1">音频</span>
            <span v-if="scope.row.resourceType===2">视频</span>
            <span v-if="scope.row.resourceType===3">文本</span>
            <span v-if="scope.row.resourceType===4">图文</span>
          </template>
        </el-table-column>
        <el-table-column label="回复内容" prop="textContent" min-width="240" show-overflow-tooltip />
        <el-table-column label="操作" align="center" fixed="right" width="90">
          <template slot-scope="scope">
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" width="800px" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="thirdWechatAutoReplyRules"
          :model="thirdWechatAutoReplyRecord"
          label-position="right"
          label-width="120px">
          <template v-if="activeName==='1'">
            <el-form-item label="请求消息类型:" prop="messageType">
              <el-select v-model="thirdWechatAutoReplyRecord.messageType" placeholder="请选择" style="width:100%">
                <el-option
                  v-for="item in messageTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>

          </template>
          <template v-if="activeName==='2'">
            <el-form-item label="匹配类型:" prop="matchingType">
              <el-select v-model="thirdWechatAutoReplyRecord.matchingType" placeholder="请选择" style="width:100%">
                <el-option
                  v-for="item in matchingTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="关键词:" prop="keyword">
              <el-input v-model="thirdWechatAutoReplyRecord.keyword" maxlength="30" show-word-limit placeholder="请输入关键词" />
            </el-form-item>
          </template>
          <el-form-item label="回复消息:" prop="replyContent">
            <material-selection ref="materialSelection2" v-model="thirdWechatAutoReplyRecord.replyContent" :app-id="listQuery.appId" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
import applicationKeySelect from '../applicationKeySelect'
import MaterialSelection from './components/materialSelection.vue'

export default {
  components: { applicationKeySelect, MaterialSelection },

  data() {
    return {
      activeName: '0',
      list: [],
      total: 0,
      listQuery: {
        appId: '',
        type: 1,
        category: 0,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      },

      multipleSelectionRecords: [],
      messageTypeOptions: [
        { value: 'text', label: '文本' },
        { value: 'image', label: '图片' },
        { value: 'voice', label: '语音' },
        { value: 'video', label: '视频' },
        { value: 'shortvideo', label: '小视频' },
        { value: 'location', label: '地理位置' },
        { value: 'link', label: '链接消息' }
      ],
      matchingTypeOptions: [
        { value: 0, label: '半匹配' },
        { value: 1, label: '全匹配' }
      ],

      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create'
      },
      thirdWechatAutoReplyRecord: {},
      thirdWechatAutoReplyRules: {
        title: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        replyContent: [
          { required: true, message: '请选择或输入回复内容', trigger: 'blur' }
        ],
        keyword: [
          { required: true, message: '请输入关键词', trigger: 'blur' }
        ],
        matchingType: [
          { required: true, message: '请选择匹配类型', trigger: 'blur' }
        ],
        messageType: [
          { required: true, message: '请选择消息类型', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    activeName: function(val) {
      this.listQuery = {
        ...this.listQuery,
        category: val
      }
      if (this.listQuery.appId) {
        this.handleFilter()
      }
    },
    'listQuery.appId': function(val) {
      this.fetchData()
    }
  },
  created() {
  },
  methods: {

    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      }
      this.fetchData()
    },
    async fetchData() {
      this.listQuery = {
        ...this.listQuery,
        replayType: this.activeName
      }
      const response = await this.$store.dispatch('thirdWechatAutoReplyPage', this.listQuery)
      this.list = response.records
      this.total = response.total
      if (this.activeName === '0') {
        this.thirdWechatAutoReplyRecord = response.records.length > 0 ? response.records[0] : {}
        this.backShowValue()
      } else {
        this.thirdWechatAutoReplyRecord = {}
      }
    },
    /* 新增*/
    handleCreate() {
      this.thirdWechatAutoReplyRecord = {
        resourceType: this.listQuery.resourceType,
        appId: this.listQuery.appId,
        replyContent: JSON.stringify({
          resourceType: 3,
          appId: this.listQuery.appId
        })
      }

      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '新增回复消息'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      var value = this.$refs.materialSelection2.getSelectValue()
      this.thirdWechatAutoReplyRecord = {
        ...this.thirdWechatAutoReplyRecord,
        ...this.assignValue(value)
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('thirdWechatAutoReplySave', this.thirdWechatAutoReplyRecord).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(row) {
      this.thirdWechatAutoReplyRecord = Object.assign({}, row) // copy obj
      this.backShowValue()
      this.sideBox.status = 'update'
      this.sideBox.recordShow = true
      this.sideBox.title = '编辑回复消息'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      var value = this.$refs.materialSelection2.getSelectValue()
      this.thirdWechatAutoReplyRecord = {
        ...this.thirdWechatAutoReplyRecord,
        id: this.thirdWechatAutoReplyRecord.id,
        resourceType: this.thirdWechatAutoReplyRecord.resourceType,
        appId: this.thirdWechatAutoReplyRecord.appId,
        ...this.assignValue(value)
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.thirdWechatAutoReplyRecord)
          this.$store.dispatch('thirdWechatAutoReplyUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      if (this.listQuery.resourceType !== 0) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }

      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('thirdWechatAutoReplyRemove', ids).then(response => {
            this.handleReset()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.$modal.msgWarning('请选择要删除的记录')
      }
    },
    handleFollowReplySave() {
      var value = this.$refs.materialSelection.getSelectValue()
      this.$store.dispatch('thirdWechatAutoReplySave', this.assignValue(value)).then(response => {
        this.$modal.msgSuccess('配置成功!')
      }).catch(() => {
      })
    },
    /**
     * 组装选择的数据
     * @param {*} value
     */
    assignValue(value) {
      var { resourceType, appId } = value
      var record = {
        replayType: this.activeName,
        resourceType: resourceType,
        appId: appId
      }
      if (resourceType === 3) {
        // 文字
        record = {
          ...record,
          textContent: value.textContent
        }
      } else if (resourceType === 0) {
        // 图片
        record = {
          ...record,
          title: value.title,
          fileUrl: value.attachment,
          mediaId: value.mediaId
        }
      } else if (resourceType === 1 || resourceType === 2) {
        // 音频、视频
        record = {
          ...record,
          title: value.title,
          textContent: value.textContent,
          mediaId: value.mediaId
        }
      } else if (resourceType === 4) {
        // 图文
        record = {
          ...record,
          articleContent: JSON.stringify(value.articleContents)
        }
      }
      return record
    },
    /**
     * 回显数据
     */
    backShowValue() {
      var { resourceType, appId, id } = this.thirdWechatAutoReplyRecord
      if (!id) {
        this.thirdWechatAutoReplyRecord = {
          ...this.thirdWechatAutoReplyRecord,
          replyContent: JSON.stringify({
            resourceType: 3,
            appId: this.listQuery.appId
          })
        }
        console.log(this.thirdWechatAutoReplyRecord)
        return
      }
      var replyContent = {
        id: id,
        resourceType: resourceType,
        appId: appId
      }
      if (resourceType === 3) {
        // 文本
        replyContent = {
          ...replyContent,
          textContent: this.thirdWechatAutoReplyRecord.textContent
        }
      }
      if (resourceType === 0) {
        // 图片
        replyContent = {
          ...replyContent,
          title: this.thirdWechatAutoReplyRecord.title,
          fileUrl: this.thirdWechatAutoReplyRecord.fileUrl,
          mediaId: this.thirdWechatAutoReplyRecord.mediaId
        }
      }
      if (resourceType === 1 || resourceType === 2) {
        // 音频、视频
        replyContent = {
          ...replyContent,
          title: this.thirdWechatAutoReplyRecord.title,
          textContent: this.thirdWechatAutoReplyRecord.textContent,
          mediaId: this.thirdWechatAutoReplyRecord.mediaId
        }
      }
      if (resourceType === 4) {
        // 图文
        replyContent = {
          ...replyContent,
          articleContents: this.thirdWechatAutoReplyRecord.articleContent ? JSON.parse(this.thirdWechatAutoReplyRecord.articleContent) : []
        }
      }
      this.thirdWechatAutoReplyRecord = {
        ...this.thirdWechatAutoReplyRecord,
        replyContent: JSON.stringify(replyContent)
      }
    }

  }
}
</script>
<style lang="scss" scope >

</style>
